// @ts-nocheck

/* model */
import Result from '@model/Result'
import MsgModel from '@model/MsgModel'
import { openTab, backToFromTab } from '@src/platform'
import * as PageType from 'pub-bbx-global/pageType/dist'
import type { openAccurateTabOptions } from 'pub-bbx-global/pageType/dist/types/PageRoutes'
import { getRouterInfo } from 'pub-bbx-global/pageType/dist/util' 
import i18n, { t } from '@src/locales'

/**
 * 用于抹平浏览器和钉钉之间的差异
 * 
 * @author dongls
 */

import { Message, MessageBox } from 'element-ui'
import { getRootWindowInitData } from '@src/util/window'
import { isFunction, isNull, isUndefined } from '@src/util/type'
// @ts-ignore
import appConfig from 'app.config';
import { onMounted } from 'vue'
import { parseInt } from 'lodash'
import { conversionLink } from '@src/util/linkSwitch';
/* enum */
import { TenantTypeEnum } from '@model/enum/TenantEnum'

const ua = window.navigator.userAgent.toLowerCase()

/**
 * 用于获取顶层window
 * 顶层window中添加了一个特殊属性[__root_window_],因此判断该属性即可
 * !注：不适合使用惰性函数改写
 * @param win - 当前窗口window对象
 */
export function getRootWindow(win: Window): Window {
  // 非frame 环境
  if (win === window.top) return win

  if (win.parent.__root_window_ == 'root') return win.parent

  return getRootWindow(win.parent)
}

/**
 * @description 用于获取DingtalkPC对象,该对象由钉钉提供
 * 由于目前只在最外层签名，所以调用钉钉api之前应先调用此方法
 */
function getDingTalkPC(): Record<string, any> {
  return getRootWindow(window).DingTalkPC
}

/**
 * @description 判断是否在钉钉内
 * !注： 由于是跨iframe获取dingtalk对象，所以instanceOf操作符不适用
 * @param dingtalk - dingtalk对象，若不传则会获取
 */
function inDingTalk(dingtalk: null | Record<string, any> = null): boolean {
  if (isNull(dingtalk) || isUndefined(dingtalk)) dingtalk = getDingTalkPC()

  if (dingtalk == null) return false

  return Boolean(dingtalk?.ua?.isDesktop)
}

/**
 * @description 抹平钉钉和浏览的alert之间的差异
 * @des 统一使用el的alert方法 单独引用命名为'FeAlert'
 * @param {String} message - 提示信息
 * @param {String} title - 标题
 * @param {String} buttonName - 按钮名称
 * @returns {Promise<Boolean>}
 */
export function alert(message: string = '', title: string = i18n.t('common.base.toast') as string, buttonName: string = i18n.t('common.base.makeSure') as string): Promise<any> {
  return MessageBox.alert(message, title, {
    confirmButtonText: buttonName
  })
  // const dingtalk = getDingTalkPC()
  // 非钉钉环境
  // if(!inDingTalk(dingtalk)) {
  // window.alert(message)
  // return Promise.resolve(true)
  // }

  // return new Promise((resolve, reject) => {
  //   dingtalk.device.notification.alert({
  //     message,
  //     // 可传空
  //     title,
  //     buttonName,
  //     onSuccess() {
  //       resolve(true)
  //     },
  //     onFail(err: any) {
  //       console.warn(err)
  //       resolve(false)
  //     }
  //   })
  // })
}

/**
 * @see http://element.eleme.io/#/zh-CN/component/message
 * 
 * @param {String} message - 提示信息 
 * @param {String} type 
 * @param {Record<string, any>} options 
 */
export function toast(message: string, type: string = 'success', options: Record<string, any> = {}): Promise<void> {
  
  return new Promise<void>((resolve, reject) => {
    // @ts-ignore
    Message({
      message,
      duration: options.duration || 1500,
      type,
      onClose() {
        resolve()
      }
    })
  })
}

/**
 * @description 抹平钉钉和浏览器confirm的差异
 * @param {String} message 
 * @param {String} title 
 */
export function confirm(message: string = '', title: string = i18n.t('common.base.toast') as string, config?: any): Promise<boolean> {
  return MessageBox.confirm(message, title, config).then(()=>true).catch(()=>false)
  // const dingtalk = getDingTalkPC()
  // if(!inDingTalk(dingtalk)) return Promise.resolve(window.confirm(message))

  // return new Promise((resolve, reject) => {  
  //   dingtalk.device.notification.confirm({
  //     message,
  //     title,
  //     buttonLabels: ['是', '否'],
  //     onSuccess(result: Record<string, any>) {
  //       resolve(result.buttonIndex == 0)
  //     },
  //     onFail(err: any) {
  //       console.warn(err)
  //       resolve(false)
  //     }
  //   });
  // });
}

/**
 * @description 在新的窗口打开链接
 * @param {String} url 
 * @param {Boolean} isNeedConvert - 是否需要转换链接
 */
function openLink(url: string, isNeedConvert = true): Window | null | void {

  if (isNeedConvert) {
    url = conversionLink(url)
  }

  let dingtalk = getDingTalkPC()

  if (!inDingTalk(dingtalk)) {
    return window.open(url)
  }

  dingtalk.biz.util.openLink({
    // 要打开链接的地址
    url
  })

}

function openView(options: Record<string, any>) {
  let rootWindow = getRootWindow(window)
  rootWindow.addTabs(options)

  if (isFunction(rootWindow.resizeFrame)) rootWindow.resizeFrame()
}

export function notification(params: Record<string, any> = {}): Promise<any> | void {
  let notificationFunction: Function = getRootWindow(window).__exports__notification
  if (!isFunction(notificationFunction)) return console.warn('[platform]: no notification function.')

  let opt: Record<string, any> = {}

  // content 会覆盖message选项 
  if (params.content) {
    opt.message = params.content
    opt.dangerouslyUseHTMLString = true
  }

  opt.customClass = params.customClass ? `base-notification ${params.customClass}` : 'base-notification'

  return notificationFunction({ ...params, ...opt })
}

export function notificationForBase<ResultType>(result: Result<ResultType> | MsgModel<ResultType>, title: string) {
  // @ts-ignore
  let isSuccess = result?.success || result?.succ || false

  notification({
    type: isSuccess ? 'success' : 'error',
    title: `${title}${isSuccess ? i18n.t('common.base.success') : i18n.t('common.base.fail')}`,
    message: isSuccess ? null : result?.message || ''
  })
}

/** 
 * @description 是否为多端环境
 * @returns {Boolean}
*/
function isMultiEnd(): boolean {
  return window.location.hostname.endsWith('linker.ltd')
}

/** 
 * @description 是否为钉钉桌面版
 * @returns {Boolean}
*/
export function isDingDingDesktop(): boolean {
  return inDingTalk()
}

/** 
 * @description 是否为钉钉网页版
 * @returns {Boolean}
*/
function isDingDingWeb(): boolean {
  return window.location.hostname.endsWith('app.shb.ltd') || window.location.hostname.endsWith('shb3144.eapps.dingtalkcloud.com')
}

/** 
 * @description 是否为钉钉版本
 * @returns {Boolean}
*/
export function isDingTalk(): boolean {
  return isDingDingDesktop() || isDingDingWeb()
}

// tenantType  0-钉钉  1-多端自建用户  2-企业微信  第三方 3-企业微信 自建 4-飞书
const rootWindowInitData = getRootWindowInitData()
export const TenantType = rootWindowInitData.tenantType || 0
// 判断是否是多端环境
export const IsMultiClient = TenantType != 0

/**
 * @description: 是否为企业微信
 * @return {Boolean}
 */
export function isQYWX(): boolean {
  return TenantType == 2 && (ua.indexOf('wxwork') >= 0 || ua.indexOf('micromessenger') >= 0)
}

// 判断用户名称或者部门名称是否需要转义 目前只有企业微信第三方应用需要 
export const isOpenData = TenantType == 2 && rootWindowInitData.IS_WECHAT_NAME == 1

export function getIsOpenData() {
  try {
    
    const rootWindowInitData = getRootWindowInitData()
    const tenantType = rootWindowInitData.tenantType || 0
    const isOpenData = tenantType == 2 && rootWindowInitData.IS_WECHAT_NAME == 1
    
    return isOpenData
    
  } catch (error) {
    
    console.error(error)
    
    return false
    
  }
}

/**
 * @description: 是否为开发环境
 * @return {Boolean}
 */
export function isDevelopment(): boolean {
  return appConfig.env == 'development'
}

// 判断是否开启显示企业微信昵称
// export const isChecked = localStorage.getItem('nickname')

// 判断企业微信昵称是否被勾选
export function isChecked() {
  const nickname = localStorage.getItem('nickname')
  return nickname && nickname === '0';
}

// 是否按钉钉或者企微或飞书组织架构选择
export function isAllotByDepartment() {
  let rootWindowInitData = getRootWindowInitData()
  let { tenantType, allotByTag } = rootWindowInitData
  return (tenantType == 0 || tenantType == 2 || tenantType == 4) && !allotByTag
}

/** 
 * @description 是否为企业微信环境
 * @returns {Boolean}
*/
export function isWorkWeiXin(): boolean {
  try {
    return window.navigator.userAgent.toLowerCase().indexOf('wxwork') > 0
  } catch (error) {
    return false
  }
}

/** 
 * @description 是否为飞书环境
 * @returns {Boolean}
*/
export function isFeiShu(): boolean {
  try {
    return window.navigator.userAgent.toLowerCase().indexOf('feishu') > 0
  } catch (error) {
    return false
  }
}

export function isNotDingTalkTenant() {

  const rootWindowInitData = getRootWindowInitData()
  const tenantType = rootWindowInitData?.tenantType || 0

  return tenantType != TenantTypeEnum.DingTalk
}


/**
 * @des 根据页面枚举定义的更加精准的项目内页面跳转方法
 */
export function openAccurateTab(options:openAccurateTabOptions, needParams:boolean = false) {
  try {
    const pageParams:any = getRouterInfo(options, t)
    console.log(pageParams, 'pageParams')
    if (document.fullscreenEnabled || document.msFullscreenEnabled ) {
      let isFull = window.fullScreen || document.webkitIsFullScreen;
      if (isFull) {
        closeFullScreen()
      }
    }
    if(needParams) return pageParams
    openTab(pageParams)

  } catch (error) {
    console.warn(error, 'error try catch');
  }

}

function closeFullScreen(){
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.msExitFullscreen) {
    document.msExitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen();
  }
}


export function backToFromAccurateTab(nowPageId:string){
  backToFromTab(nowPageId)
}


export default {
  isAllotByDepartment,
  isChecked,
  TenantType,
  IsMultiClient,
  getRootWindow,
  getDingTalkPC,
  inDingTalk,
  alert,
  confirm,
  openView,
  toast,
  openLink,
  notification,
  isMultiEnd,
  isDingDingDesktop,
  isDingDingWeb,
  isDingTalk,
  isQYWX,
  notificationForBase,
  isOpenData,
  isWorkWeiXin,
  isNotDingTalkTenant,
  openTab,
  isFeiShu,
  openAccurateTab
};